<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //创建label标签
        let proText = document.createElement('label');
        proText.innerHTML = '请选择省份';//添加到label
        document.body.appendChild(proText);//追加到界面

        //准备省份的数据
        let proArr = ['河南省','湖北省','浙江省'];
        let proSelect = document.createElement('select');
        for(let i=0;i<proArr.length;i++) {
            let option = document.createElement('option');
            option.innerHTML=proArr[i];
            option.value = i;//给省增加value属性，方便后面选择省市时获取
            proSelect.appendChild(option);
        }
        
        //新增省份对应的select标签
        document.body.appendChild(proSelect);

        //准备城市的数据
        let henanCity = ['郑州','新乡','焦作'];
        let hubeiCity = ['武汉','黄冈','随州','恩施'];
        let zhejiangCity = ['杭州','舟山','宁波','丽水','衢州'];
        let cityArr = [];
        cityArr.push(henanCity);
        cityArr.push(hubeiCity);
        cityArr.push(zhejiangCity);
        let citySelect = document.createElement('select');
        //显示默认
        for(let index=0;index < cityArr.length;index++){
            let option = document.createElement('option');
            option.innerHTML=cityArr[0][index];
            citySelect.appendChild(option);
        }

        //新增城市对应的select标签
        document.body.appendChild(citySelect);

        //相应用户操作
        
        proSelect.onchange = function(e){
            //console.log(e.target.value);
            //console.log(this.value);
            //两种方法输出的值一样，当前所选择的省份的下标

            //删除之前的城市
            let opt = citySelect.children;//获取citySelect的子元素并赋值给opt

            for(let index =opt.length-1;index >=0;index--){
                //for循环--，根据元素个数删除旗下子元素，用++会跳过其中的某些元素，有数据残留
                //因为index增大，而opn.length在减小。所以循环条件不满足了
                console.log(opt[index]);
                citySelect.removeChild(opt[index]);
                
            }

           //添加选择的省份下的城市
            for(let index=0;index < cityArr[this.value].length;index++){
                let option = document.createElement('option');
                option.innerHTML=cityArr[this.value][index];
                citySelect.appendChild(option);
            }
            document.body.appendChild(citySelect);
        }
    </script>
</body>
</html>